<template>
  <div class="i_bg">
    <div class="content mar_20">
      <img src="@/assets/images/img1.jpg" />
    </div>

    <!--Begin 第一步：查看购物车 Begin -->
    <div class="content mar_20">
      <table
        border="0"
        class="car_tab"
        style="width: 1200px; margin-bottom: 50px; text-align: center"
        cellspacing="0"
        cellpadding="0"
      >
        <tr>
          <td class="car_th" width="490">商品名称</td>
          <td class="car_th" width="150">购买数量</td>
          <td class="car_th" width="130">小计</td>
          <td class="car_th" width="150">操作</td>
        </tr>
        <template v-if="order != null && order.orderDetailList">
          <tr
            v-for="orderDetail in order.orderDetailList"
            :key="orderDetail.productId"
          >
            <td>
              <div class="c_s_img">
                <img
                  :src="imagesDir + orderDetail.fileName"
                  width="73"
                  height="73"
                />
              </div>
              {{ orderDetail.name }}
            </td>
            <td align="center">
              <div class="c_num">
                <input
                  type="button"
                  value=""
                  @click="subUpdata(orderDetail.productId, 1)"
                  class="car_btn_1"
                />
                <input
                  v-if="quantityListNow"
                  type="text"
                  v-model.number="quantityListNow[orderDetail.productId]"
                  @blur="validData(orderDetail.productId)"
                  name=""
                  class="car_ipt"
                />
                <input
                  type="button"
                  value=""
                  @click="addUpdate(orderDetail.productId, 1)"
                  class="car_btn_2"
                />
              </div>
            </td>
            <td align="center" style="color: #ff4e00">
              ￥{{ orderDetail.cost * orderDetail.quantity }}
            </td>
            <td align="center">
              <a
                @click="
                  deleteProductList(
                    orderDetail.productId,
                    quantityListNow[orderDetail.productId]
                  )
                "
                href="javascript:;"
                >删除</a
              >&nbsp; &nbsp;
            </td>
          </tr>
        </template>
        <tr>
          <td colspan="4">
            <el-empty
              v-if="
                order == null ||
                order.orderDetailList == null ||
                order.cost <= 0
              "
              description="空空如也，赶紧去购买商品吧~"
            ></el-empty>
          </td>
        </tr>
        <tr>
          <td align="left">
            <button class="clear-cart-btn" @click="clearAllProductList()">
              清空购物车
            </button>
          </td>
          <td align="right" colspan="3">
            <span style="font-size: 1rem">商品总价：</span><span style="color:red;font-size:2rem">￥{{order.cost}}</span>
          </td>
        </tr>
        <tr valign="top" height="150">
          <td colspan="4" align="right">
            <router-link :to="{ name: 'GoodsList' }"
              ><img src="@/assets/images/buy1.gif" /></router-link
            >&nbsp; &nbsp;
            <router-link :to="{name: 'OrderConfirm'}"><img src="@/assets/images/buy2.gif" /></router-link>
          </td>
        </tr>
      </table>
    </div>
    <!--End 第一步：查看购物车 End-->
  </div>
</template>

<script>
import Vue from "vue";
import { Empty } from "element-ui";
Vue.use(Empty);
export default {
  data() {
    return {
      order: null,
      quantityListLast: {}, //修改前的购物车商品数量
      quantityListNow: {}, //修改后购物车商品数量
      imagesDir: sessionStorage.getItem("imagesDir"),
    };
  },
  methods: {
    subUpdata(pId, num) { //num传入始终为整数，表示减多少
      //减少购物车商品数量，直接恢复es和数据库中库存
      this.$axios({
        url: "/api/product/detail",
        method: "POST",
        data: {
          id: pId,
        },
      }).then((rs) => {
        //1.当期页面展示效果商品数量 -num, 2. 修改购物车中的数据
        this.quantityListLast[pId] = this.quantityListNow[pId] =
          this.quantityListLast[pId] - num;
        this.modifyOrderCar(pId, -num); // -num
        let product = rs.data.product;
        //直接修改es和数据库中的商品数量
        product.stock += num;
        this.$axios({
          url: "/api/product/update0",
          method: "POST",
          data: product,
        }).then((rs) => {
          console.log("修改es单个商品结果", rs.data.msg);
        });
      });
    },
    addUpdate(pId, num) { //num传入始终为整数，表示加多少
      //新增购物车商品数量，需要判断是否有如此多库存
      this.$axios({
        url: "/api/product/detail",
        method: "POST",
        data: {
          id: pId,
        },
      }).then((rs) => {
        let product = rs.data.product;
        if (product.stock >= num) {
          this.quantityListLast[pId] = this.quantityListNow[pId] =
          this.quantityListLast[pId] + num;
          this.modifyOrderCar(pId, num); // +num
          product.stock -= num;
          this.$axios({
            url: "/api/product/update0",
            method: "POST",
            data: product,
          }).then((rs) => {
            console.log("修改es单个商品结果", rs.data.msg);
          });
        } else {
          this.$message.warning("商品库存不够！");
        }
      });
    },
    //修改购物车中展示的数据， redis修改
    modifyOrderCar(pId, num) {
      //只有两种情况： 1.数量 +- num,  2：数量归零，直接从该购物车订单数组中删除该对象
      let delIndex = -1;
      for (let i = 0; i < this.order.orderDetailList.length; i++) {
        if (this.order.orderDetailList[i].productId == pId) {
          this.order.orderDetailList[i].quantity += num;
          this.order.cost += num * this.order.orderDetailList[i].cost;
          if (this.order.orderDetailList[i].quantity == 0) {
            //从购物车订单中删除
            delIndex = i;
          }
          // console.log("修改了pId为：" + pId, "num为：" + num)
          // console.log("购物车quantity：" + this.order.orderDetailList[i].quantity)
          //修改redis中购物车订单信息
        }
      }
      if (delIndex != -1) {
        this.order.orderDetailList = this.order.orderDetailList.filter(
          (item, index) => index != delIndex
        );
        console.log(
          "-----------------存在quantity为0的商品，将删除-------------------",
          this.order.orderDetailList
        );
      }
      this.$axios({
        url: "/api/order/modify",
        method: "POST",
        data: this.order,
      }).then((rs) => {
        console.log("redis中购物车订单修改结果", rs.data.msg);
      });
    },
    //将购物车中的整个商品删除
    deleteProductList(pId, num) {
      if (confirm("是否要将该商品从购物车中清空？")) {
        this.subUpdata(pId, num);
      }
    },
    //清空购物车
    clearAllProductList() {
      if (confirm("是否要清空整个购物车？")) {
        for (const productId in this.quantityListNow) {
          this.subUpdata(productId, this.quantityListNow[productId]);
        }
      }
    },
    //校验手动输入的商品库存数据，这里
    validData(pId) {
      // 将输入转换为数字
      let num = Number(this.quantityListNow[pId]);
      // 检查是否为有效数字
      if (isNaN(num)) {
        return 1;
      }
      // 保证为整数
      num = Math.round(num);
      // 确保最小值至少为1，为0就清空了
      if(num <= 0) {
          num = Math.max(1, num);
          this.quantityListNow[pId] = num;
      }
      //判断是否增加了
      if(num == this.quantityListLast[pId]) { 
          console.log("没变化")
      }else if(num > this.quantityListLast[pId]) { //类似于addUpdate方法
          //请求看库存是否够，不够说明当前输入的值太大了，需要回撤到之前历史quantityListLast
          this.$axios({
            url: "/api/product/detail",
            method: "POST",
            data: {
              id: pId,
            },
          }).then((rs) => {
              let product = rs.data.product;
              if (product.stock >= num) {
                this.quantityListLast[pId] = this.quantityListNow[pId];
                //成功才修改，否则将值绑定为之前的
                this.modifyOrderCar(pId, num); // +num
                product.stock -= num;
                this.$axios({
                  url: "/api/product/update0",
                  method: "POST",
                  data: product,
                }).then((rs) => {
                  console.log("修改es单个商品结果", rs.data.msg);
                });
              } else {
                this.$message.warning("商品库存不够！");
                this.quantityListNow[pId] = this.quantityListLast[pId];
              }
            });
          
          console.log("库存够就购物车商品数量就新增了")
      }else { //类似于subUpdate方法
          let digit = this.quantityListLast[pId] - num;
          this.subUpdata(pId, digit);
          this.quantityListLast[pId] = num;
          console.log("购物车商品数量减少了");
      }

    },
  },
  watch: {
    order: {
      deep: true,
      handler(newOrder) {
        this.$store.commit("setOrder", newOrder);
      },
    },
  },
  created() {
    let type = sessionStorage.getItem("type");
    if(!type) {
      this.$message.error("权限不足，将回到首页！")
      this.$router.push({
        name: 'IndexCenter'
      })
      return;
    }
    this.order = this.$store.state.order;
    //初始化
    this.order.orderDetailList.forEach((i) => {
      this.quantityListLast[i.productId] = i.quantity;
      this.$set(this.quantityListNow, i.productId, i.quantity);
    });
  },
};
</script>

<style scope>
.clear-cart-btn {
  background-color: #ff4757;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.clear-cart-btn:hover {
  background-color: #ff3742;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.clear-cart-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
</style>